# SA2410.ZCE

from app_config import get_pro
import re
from pandas import DataFrame

pro = get_pro()


def to_chart(f_name: str, data: DataFrame):

    data['pct_change'] = data['value'].pct_change()

    xdata = data['col3'].tolist()
    ydata = data['pct_change'].dropna().tolist()


    from pyecharts.charts import Bar
    from pyecharts.charts import Line
    from pyecharts.options import TitleOpts
    from datetime import datetime

    # 创建条形图
    bar = Bar()
    bar.add_xaxis(xdata)  # X 轴数据
    bar.add_yaxis("示例数据", ydata)  # Y 轴数据

    # 设置全局配置项
    bar.set_global_opts(title_opts=TitleOpts(title="日期示例"))

    # 渲染图表到 HTML 文件
    bar.render('date_example.html')

    line = Line()
    line.add_xaxis(xdata)
    line.add_yaxis(f_name, ydata)
    line.render("./f_chart/percent/" + f_name + "line.html")
    pass


def to_chart1(f_name: str, data: DataFrame):

    xdata = data['col3'].tolist()
    ydata = data['value'].tolist()

    # 计算平均值
    average = round(sum(ydata) / len(ydata))

    # 每个元素减去平均值
    result = [x - average for x in ydata]

    from pyecharts.charts import Bar
    from pyecharts.charts import Line
    from pyecharts.options import TitleOpts
    from datetime import datetime
    from pyecharts import options as opts

    # 创建条形图
    bar = Bar()
    bar.add_xaxis(xdata)  # X 轴数据
    bar.add_yaxis("示例数据", ydata)  # Y 轴数据

    # 设置全局配置项
    bar.set_global_opts(title_opts=TitleOpts(title="日期示例"))

    # 渲染图表到 HTML 文件
    bar.render('date_example.html')

    line = Line()
    line.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    line.add_xaxis(xdata)
    line.add_yaxis(average.__str__() + ' / ' + datetime.now().strftime("%Y-%m-%d %H:%M:%S"), result)
    line.render("./f_chart/value/" + f_name + "line.html")
    pass


if __name__ == '__main__':
    import pandas as pd

    # 读取文件，指定分隔符为空格（\s+ 匹配一个或多个空格）
    df = pd.read_csv('example.txt', sep='\s+', header=None, names=['col1', 'col2', 'col3', 'value'])

    # 按 col1 分组
    grouped = df.groupby('col1')

    # 遍历每个分组并打印
    for group_name, group_df in grouped:
        print(f"\nGroup: {group_name}")
        print(group_df)
        print(type(group_df))
        to_chart(group_name, group_df)
        to_chart1(group_name, group_df)

